package com.example.demo.security;


import io.jsonwebtoken.Claims;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ServletContextPropertyUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//在Filter中对Jwt进行验证
@Component
public class JwtRequestFilter extends OncePerRequestFilter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException{
        final String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        if(Strings.isEmpty(header) || !header.startsWith("Bearer ")){
            chain.doFilter(request,response);
            return;
        }
        try{
            final String token = header.substring(7);
            //解析Token，若Token不合法会抛出异常
            Claims claims = jwtTokenUtil.getClaimFromToken(token);
            //验证Claims
            UserDetails userDetails = userDetailsService.loadUserByUsername(claims.getSubject());
            if(userDetails != null && jwtTokenUtil.validateClaim(claims,userDetails)){
                //创建一个Token放入context中，后面的Filter可以使用
                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }

        }catch (Exception e){
            logger.warn(e);
        }
        chain.doFilter(request,response);
    }
}
